import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'dart:io';
import '../models/posts.dart';
import '../services/posts_service.dart';
import '../services/upload_service.dart';

class PostsListPage extends StatefulWidget {
  const PostsListPage({super.key});

  @override
  State<PostsListPage> createState() => _PostsListPageState();
}

class _PostsListPageState extends State<PostsListPage> with SingleTickerProviderStateMixin {
  final PostsService _postsService = PostsService();
  List<Posts> _posts = [];
  bool _isLoading = true;
  String? _errorMessage;
  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _tabController.addListener(() {
      // 当tab切换时，更新浮动按钮的显示状态
      setState(() {});
    });
    _loadPosts();
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  Future<void> _loadPosts() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      final list = await _postsService.getAllPosts();
      setState(() {
        _isLoading = false;
        _posts = list;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
        _errorMessage = '$e';
        _posts = [];
      });
    }
  }

  void _showSearchDialog() {
    Navigator.pushNamed(context, '/search');
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.menu, color: Colors.black),
          onPressed: null,
        ),
        title: TabBar(
          controller: _tabController,
          indicatorColor: Colors.red,
          indicatorWeight: 2.0,
          indicatorSize: TabBarIndicatorSize.label,
          dividerColor: Colors.transparent,
          labelColor: Colors.black,
          unselectedLabelColor: Colors.grey,
          tabs: const [
            Tab(text: '发现'),
            Tab(text: '我的'),
          ],
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.add_circle_outline, color: Colors.black, size: 26),
            onPressed: _navigateToAddPost,
            tooltip: '发布动态',
          ),
          IconButton(
            icon: const Icon(Icons.search, color: Colors.black),
            onPressed: _showSearchDialog,
            tooltip: '搜索',
          ),
        ],
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          // "发现" tab - 显示所有帖子
          _buildDiscoverTab(),
          // "我的" tab - 显示我的发布和我的点赞
          _buildMyPostsTab(),
        ],
      ),
    );
  }

  Widget _buildDiscoverTab() {
    return _buildBody();
  }

  Widget _buildMyPostsTab() {
    return _MyPostsTab(postsService: _postsService);
  }

  Widget _buildBody() {
    if (_isLoading) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }

    if (_errorMessage != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.error_outline,
              size: 64,
              color: Colors.grey[400],
            ),
            const SizedBox(height: 16),
            Text(
              _errorMessage!,
              style: TextStyle(color: Colors.grey[600]),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: _loadPosts,
              child: const Text('重试'),
            ),
          ],
        ),
      );
    }

    if (_posts.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.description_outlined,
              size: 64,
              color: Colors.grey[400],
            ),
            const SizedBox(height: 16),
            Text(
              '暂无帖子',
              style: TextStyle(color: Colors.grey[600]),
            ),
            const SizedBox(height: 8),
            TextButton(
              onPressed: _navigateToAddPost,
              child: const Text('创建第一个帖子'),
            ),
          ],
        ),
      );
    }

    return RefreshIndicator(
      onRefresh: _loadPosts,
      child: MasonryGridView.count(
        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
        crossAxisCount: 2,
        mainAxisSpacing: 8,
        crossAxisSpacing: 8,
        itemCount: _posts.length,
        itemBuilder: (context, index) {
          return _buildWaterfallItem(_posts[index]);
        },
      ),
    );
  }

  Widget _buildWaterfallItem(Posts post) {
    final String? cover = post.imageUrls.isNotEmpty
        ? post.imageUrls.first
        : post.imageUrl;
    return GestureDetector(
      onTap: () async {
        if (post.id != null) {
          // 等待详情页返回更新后的帖子信息
          final updatedPost = await Navigator.pushNamed(context, '/postDetail', arguments: post.id);
          
          // 如果返回了更新后的帖子，更新列表中对应的帖子
          if (updatedPost != null && updatedPost is Posts) {
            setState(() {
              final index = _posts.indexWhere((p) => p.id == updatedPost.id);
              if (index != -1) {
                _posts[index] = updatedPost;
              }
            });
          }
        }
      },
      child: Card(
        clipBehavior: Clip.antiAlias,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        elevation: 1,
        child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (cover != null && cover.isNotEmpty)
            Image.network(
              cover,
              width: double.infinity,
              fit: BoxFit.cover,
              errorBuilder: (_, __, ___) => Container(
                height: 120,
                color: Colors.grey[200],
                child: const Icon(Icons.broken_image, color: Colors.grey),
              ),
            ),
          if (post.title.isNotEmpty)
            Padding(
              padding: const EdgeInsets.fromLTRB(12, 12, 12, 6),
              child: Text(
                post.title,
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w700,
                ),
              ),
            ),
          if (post.content.isNotEmpty)
            Padding(
              padding: const EdgeInsets.fromLTRB(12, 0, 12, 12),
              child: Text(
                post.content,
                style: const TextStyle(fontSize: 14, height: 1.4),
              ),
            ),
          Padding(
            padding: const EdgeInsets.fromLTRB(12, 0, 12, 12),
            child: Row(
              children: [
                // 用户头像
                CircleAvatar(
                  radius: 12,
                  backgroundColor: Colors.grey[300],
                  backgroundImage: (post.avatarUrl != null && post.avatarUrl!.isNotEmpty)
                      ? NetworkImage(post.avatarUrl!)
                      : null,
                  child: (post.avatarUrl == null || post.avatarUrl!.isEmpty)
                      ? Icon(Icons.person, size: 14, color: Colors.grey[600])
                      : null,
                ),
                const SizedBox(width: 8),
                // 用户名
                Expanded(
                  child: Text(
                    post.userName.isNotEmpty ? post.userName : '匿名',
                    style: TextStyle(fontSize: 12, color: Colors.grey[700], fontWeight: FontWeight.w500),
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                // 点赞数（始终显示）
                Icon(
                  post.isLiked ? Icons.favorite : Icons.favorite_border,
                  size: 14,
                  color: post.isLiked ? Colors.redAccent : Colors.grey[500],
                ),
                const SizedBox(width: 4),
                Text(
                  '${post.likes ?? 0}',
                  style: TextStyle(fontSize: 12, color: Colors.grey[600]),
                ),
              ],
            ),
          ),
        ],
        ),
      ),
    );
  }

  void _navigateToAddPost() async {
    final result = await Navigator.pushNamed(context, '/addPost');
    if (result == true) {
      _loadPosts();
    }
  }
}

// "我的"标签页 - 包含"我的发布"和"我的点赞"两个子标签
class _MyPostsTab extends StatefulWidget {
  final PostsService postsService;

  const _MyPostsTab({required this.postsService});

  @override
  State<_MyPostsTab> createState() => _MyPostsTabState();
}

class _MyPostsTabState extends State<_MyPostsTab> with SingleTickerProviderStateMixin {
  late TabController _subTabController;
  List<Posts> _myPosts = [];
  List<Posts> _likedPosts = [];
  bool _isLoadingMyPosts = true;
  bool _isLoadingLikedPosts = true;
  String? _errorMessageMyPosts;
  String? _errorMessageLikedPosts;
  String? _backgroundImageUrl;
  final UploadService _uploadService = UploadService();
  static const String _backgroundImageKey = 'my_posts_background_image';

  @override
  void initState() {
    super.initState();
    _subTabController = TabController(length: 2, vsync: this);
    _loadBackgroundImage();
    _loadMyPosts();
    _loadLikedPosts();
  }

  Future<void> _loadBackgroundImage() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final url = prefs.getString(_backgroundImageKey);
      if (mounted) {
        setState(() {
          _backgroundImageUrl = url;
        });
      }
    } catch (e) {
      print('❌ 加载背景图片失败: $e');
    }
  }

  Future<void> _saveBackgroundImage(String url) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString(_backgroundImageKey, url);
    } catch (e) {
      print('❌ 保存背景图片失败: $e');
    }
  }

  Future<void> _changeBackgroundImage() async {
    try {
      final file = await _uploadService.pickImage();
      if (file == null) return;

      // 显示上传进度
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) => const Center(
          child: CircularProgressIndicator(),
        ),
      );

      // 上传图片
      final url = await _uploadService.uploadImage(file);
      
      if (!mounted) return;
      Navigator.pop(context); // 关闭进度对话框

      // 保存URL
      await _saveBackgroundImage(url);
      
      if (mounted) {
        setState(() {
          _backgroundImageUrl = url;
        });
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('背景图片更换成功')),
        );
      }
    } catch (e) {
      if (!mounted) return;
      Navigator.pop(context); // 关闭进度对话框
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('更换失败: $e'), backgroundColor: Colors.red),
      );
    }
  }

  @override
  void dispose() {
    _subTabController.dispose();
    super.dispose();
  }

  Future<void> _loadMyPosts() async {
    setState(() {
      _isLoadingMyPosts = true;
      _errorMessageMyPosts = null;
    });

    try {
      print('🔄 开始加载我的发布...');
      final list = await widget.postsService.getMyPosts();
      print('✅ 加载完成，获取到 ${list.length} 条帖子');
      setState(() {
        _isLoadingMyPosts = false;
        _myPosts = list;
      });
    } catch (e, stackTrace) {
      print('❌ 加载我的发布失败: $e');
      print('   堆栈跟踪: $stackTrace');
      setState(() {
        _isLoadingMyPosts = false;
        _errorMessageMyPosts = '$e';
        _myPosts = [];
      });
    }
  }

  Future<void> _loadLikedPosts() async {
    setState(() {
      _isLoadingLikedPosts = true;
      _errorMessageLikedPosts = null;
    });

    try {
      print('🔄 开始加载我的点赞...');
      final list = await widget.postsService.getLikedPosts();
      print('✅ 加载完成，获取到 ${list.length} 条帖子');
      setState(() {
        _isLoadingLikedPosts = false;
        _likedPosts = list;
      });
    } catch (e, stackTrace) {
      print('❌ 加载我的点赞失败: $e');
      print('   堆栈跟踪: $stackTrace');
      setState(() {
        _isLoadingLikedPosts = false;
        _errorMessageLikedPosts = '$e';
        _likedPosts = [];
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        // 背景图片区域
        Stack(
          children: [
            Container(
              height: 200,
              width: double.infinity,
              color: Colors.grey[200],
              child: _backgroundImageUrl != null && _backgroundImageUrl!.isNotEmpty
                  ? CachedNetworkImage(
                      imageUrl: _backgroundImageUrl!,
                      fit: BoxFit.cover,
                      placeholder: (context, url) => Container(
                        color: Colors.grey[200],
                        child: Center(
                          child: CircularProgressIndicator(
                            strokeWidth: 2,
                            color: Colors.grey[400],
                          ),
                        ),
                      ),
                      errorWidget: (context, url, error) => Container(
                        color: Colors.grey[200],
                        child: Center(
                          child: Icon(
                            Icons.image,
                            size: 48,
                            color: Colors.grey[400],
                          ),
                        ),
                      ),
                      memCacheWidth: (MediaQuery.of(context).size.width * 2).toInt(),
                      memCacheHeight: 400,
                    )
                  : Center(
                      child: Icon(
                        Icons.image,
                        size: 48,
                        color: Colors.grey[400],
                      ),
                    ),
            ),
            // 更换背景图片按钮
            Positioned(
              top: 8,
              right: 8,
              child: IconButton(
                icon: Container(
                  padding: const EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: Colors.black.withOpacity(0.5),
                    shape: BoxShape.circle,
                  ),
                  child: const Icon(
                    Icons.edit,
                    color: Colors.white,
                    size: 20,
                  ),
                ),
                onPressed: _changeBackgroundImage,
                tooltip: '更换背景',
              ),
            ),
          ],
        ),
        // 子TabBar
        Container(
          color: Colors.white,
          child: TabBar(
            controller: _subTabController,
            indicatorColor: Colors.red,
            indicatorWeight: 2.0,
            indicatorSize: TabBarIndicatorSize.label,
            dividerColor: Colors.transparent,
            labelColor: Colors.black,
            unselectedLabelColor: Colors.grey,
            tabs: const [
              Tab(text: '我的发布'),
              Tab(text: '我的点赞'),
            ],
          ),
        ),
        // 子TabBarView
        Expanded(
          child: TabBarView(
            controller: _subTabController,
            children: [
              _buildMyPostsView(),
              _buildLikedPostsView(),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildMyPostsView() {
    if (_isLoadingMyPosts) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_errorMessageMyPosts != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.error_outline, size: 64, color: Colors.grey[400]),
            const SizedBox(height: 16),
            Text(_errorMessageMyPosts!, style: TextStyle(color: Colors.grey[600])),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: _loadMyPosts,
              child: const Text('重试'),
            ),
          ],
        ),
      );
    }

    if (_myPosts.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.description_outlined, size: 64, color: Colors.grey[400]),
            const SizedBox(height: 16),
            Text('还没有发布过帖子', style: TextStyle(color: Colors.grey[600])),
            const SizedBox(height: 8),
            ElevatedButton(
              onPressed: () {
                Navigator.pushNamed(context, '/addPost');
              },
              child: const Text('发布第一个帖子'),
            ),
          ],
        ),
      );
    }

    return RefreshIndicator(
      onRefresh: _loadMyPosts,
      child: MasonryGridView.count(
        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
        crossAxisCount: 2,
        mainAxisSpacing: 8,
        crossAxisSpacing: 8,
        itemCount: _myPosts.length,
        itemBuilder: (context, index) {
          return _buildPostItem(_myPosts[index]);
        },
      ),
    );
  }

  Widget _buildLikedPostsView() {
    if (_isLoadingLikedPosts) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_errorMessageLikedPosts != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.error_outline, size: 64, color: Colors.grey[400]),
            const SizedBox(height: 16),
            Text(_errorMessageLikedPosts!, style: TextStyle(color: Colors.grey[600])),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: _loadLikedPosts,
              child: const Text('重试'),
            ),
          ],
        ),
      );
    }

    if (_likedPosts.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.favorite_border, size: 64, color: Colors.grey[400]),
            const SizedBox(height: 16),
            Text('还没有点赞过帖子', style: TextStyle(color: Colors.grey[600])),
          ],
        ),
      );
    }

    return RefreshIndicator(
      onRefresh: _loadLikedPosts,
      child: MasonryGridView.count(
        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
        crossAxisCount: 2,
        mainAxisSpacing: 8,
        crossAxisSpacing: 8,
        itemCount: _likedPosts.length,
        itemBuilder: (context, index) {
          return _buildPostItem(_likedPosts[index]);
        },
      ),
    );
  }

  Widget _buildPostItem(Posts post) {
    final String? cover = post.imageUrls.isNotEmpty
        ? post.imageUrls.first
        : post.imageUrl;
    return GestureDetector(
      onTap: () async {
        if (post.id != null) {
          final updatedPost = await Navigator.pushNamed(context, '/postDetail', arguments: post.id);
          
          if (updatedPost != null && updatedPost is Posts) {
            setState(() {
              // 更新对应列表中的帖子
              final myIndex = _myPosts.indexWhere((p) => p.id == updatedPost.id);
              if (myIndex != -1) {
                _myPosts[myIndex] = updatedPost;
              }
              
              final likedIndex = _likedPosts.indexWhere((p) => p.id == updatedPost.id);
              if (likedIndex != -1) {
                // 如果取消点赞，从点赞列表中移除
                if (!updatedPost.isLiked) {
                  _likedPosts.removeAt(likedIndex);
                } else {
                  _likedPosts[likedIndex] = updatedPost;
                }
              } else if (updatedPost.isLiked) {
                // 如果点赞了，添加到点赞列表
                _likedPosts.add(updatedPost);
              }
            });
          }
        }
      },
      child: Card(
        clipBehavior: Clip.antiAlias,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        elevation: 1,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (cover != null && cover.isNotEmpty)
              Image.network(
                cover,
                width: double.infinity,
                fit: BoxFit.cover,
                errorBuilder: (_, __, ___) => Container(
                  height: 120,
                  color: Colors.grey[200],
                  child: const Icon(Icons.broken_image, color: Colors.grey),
                ),
              ),
            if (post.title.isNotEmpty)
              Padding(
                padding: const EdgeInsets.fromLTRB(12, 12, 12, 6),
                child: Text(
                  post.title,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w700,
                  ),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            if (post.content.isNotEmpty)
              Padding(
                padding: const EdgeInsets.fromLTRB(12, 0, 12, 12),
                child: Text(
                  post.content,
                  style: const TextStyle(fontSize: 14, height: 1.4),
                  maxLines: 3,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            Padding(
              padding: const EdgeInsets.fromLTRB(12, 0, 12, 12),
              child: Row(
                children: [
                  CircleAvatar(
                    radius: 12,
                    backgroundColor: Colors.grey[300],
                    backgroundImage: (post.avatarUrl != null && post.avatarUrl!.isNotEmpty)
                        ? NetworkImage(post.avatarUrl!)
                        : null,
                    child: (post.avatarUrl == null || post.avatarUrl!.isEmpty)
                        ? Icon(Icons.person, size: 14, color: Colors.grey[600])
                        : null,
                  ),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      post.userName.isNotEmpty ? post.userName : '匿名',
                      style: TextStyle(fontSize: 12, color: Colors.grey[700], fontWeight: FontWeight.w500),
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  Icon(
                    post.isLiked ? Icons.favorite : Icons.favorite_border,
                    size: 14,
                    color: post.isLiked ? Colors.redAccent : Colors.grey[500],
                  ),
                  const SizedBox(width: 4),
                  Text(
                    '${post.likes ?? 0}',
                    style: TextStyle(fontSize: 12, color: Colors.grey[600]),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}



